package control.control.authmanage;


import base.bean.StandardResponse;
import base.standard.constant.message.MessageCode;
import base.util.BeanUtil;
import base.util.ResponseUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import control.module.bo.authmanage.RoleAuthBo;
import control.module.po.authmanage.RoleAuth;
import control.module.vo.authmanage.RoleAuthVO;
import control.service.IAuthService;
import control.service.IRoleAuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

/**
 * <p>
 * 角色权限表(角色绑定权限相关) 前端控制器
 * </p>
 *
 * @author cyj
 * @since 2020-10-21
 */
@RestController
@RequestMapping("/role/auth/{roleId}")
@ResponseStatus(code = HttpStatus.OK)
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class RoleAuthController {

    @Autowired
    private IRoleAuthService roleAuthService;

    @Autowired
    private IAuthService authService;

    @GetMapping("/all")
    public StandardResponse getRoleAuths(Page page, @PathVariable Integer roleId) {
        IPage<RoleAuth> list = roleAuthService.page(page, new QueryWrapper<>(new RoleAuth().setRoleId(roleId)));
        IPage<RoleAuthVO> roleAuthVos = BeanUtil.newInstanceAndCopyBatch(list, RoleAuthVO.class);
        roleAuthVos.getRecords().stream().forEach(roleAuthVO ->
                Optional.ofNullable(authService.getById(roleAuthVO.getAuthId())).ifPresent(auth -> {
                    roleAuthVO.setAuth(auth.getAuth());
                }));
        return ResponseUtil.success(roleAuthVos);
    }

    @PostMapping
    public StandardResponse saveRoleAuths(@PathVariable Integer roleId,
                                          @RequestBody @Validated List<RoleAuthBo> roleAuthBos) {
        boolean deleteResult = roleAuthService.removeByRoleId(roleId);
        log.info("delete [{}] auths", roleId);
        List<RoleAuth> roleAuths = BeanUtil.newInstanceAndCopyBatch(roleAuthBos, RoleAuth.class);
        boolean saveResult = roleAuthService.saveBatch(roleAuths);
        log.info("save [{}] auths, result[{}]", roleId, saveResult);
        return ResponseUtil.success(MessageCode.ROLE_AUTH_SAVE, saveResult);
    }
}

